package com.roads.engineering.service.impl;

import com.roads.common.config.MasterConfig;
import com.roads.common.constant.Constants;
import com.roads.common.core.domain.entity.SysUser;
import com.roads.common.core.text.Convert;
import com.roads.common.utils.DateUtils;
import com.roads.common.utils.SecurityUtils;
import com.roads.common.utils.file.FileUtils;
import com.roads.common.utils.uuid.IdUtils;
import com.roads.engineering.domain.EngMeterageChange;
import com.roads.engineering.domain.EngMeterageContract;
import com.roads.engineering.domain.EngMeterageDetailAnnex;
import com.roads.engineering.domain.EngMeterageExplain;
import com.roads.engineering.domain.EngMeterageMaster;
import com.roads.engineering.domain.EngMeterageOther;
import com.roads.engineering.mapper.EngMeterageChangeMapper;
import com.roads.engineering.mapper.EngMeterageContractMapper;
import com.roads.engineering.mapper.EngMeterageDetailAnnexMapper;
import com.roads.engineering.mapper.EngMeterageExplainMapper;
import com.roads.engineering.mapper.EngMeterageMasterMapper;
import com.roads.engineering.mapper.EngMeterageOtherMapper;
import com.roads.engineering.service.IEngMeterageDetailService;
import com.roads.project.domain.ProBoqMeterage;
import com.roads.project.domain.ProPaymentItems;
import com.roads.project.mapper.ProBoqMeterageMapper;
import com.roads.project.mapper.ProPaymentItemsMapper;
import com.roads.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName EngMeterageDetailServiceImpl
 * @Description 工程计量细表Service业务层处理
 * @Author nhp
 * @Date 2022/3/1 0001 17:27
 * @Version 1.0.0
 **/
@Service
public class EngMeterageDetailServiceImpl implements IEngMeterageDetailService {

    @Autowired
    private EngMeterageContractMapper detailContractMapper;

    @Autowired
    private EngMeterageChangeMapper detailChangeMapper;

    @Autowired
    private EngMeterageOtherMapper detailOtherMapper;

    @Autowired
    private EngMeterageExplainMapper detailExplainMapper;

    @Autowired
    private ProBoqMeterageMapper meterageMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private EngMeterageMasterMapper masterMapper;

    @Autowired
    private EngMeterageDetailAnnexMapper detailAnnexMapper;

    @Autowired
    private ProPaymentItemsMapper paymentItemsMapper;

    /**
     * 查询工程计量合同清单列表
     *
     * @param model 工程计量合同清单实体
     * @return 工程计量合同清单集合
     */
    @Override
    public List<EngMeterageContract> selectContractList(EngMeterageContract model) {
        return detailContractMapper.selectModelList(model);
    }

    /**
     * 查询工程计量变更清单列表
     *
     * @param model 工程计量变更清单实体
     * @return 工程计量变更清单集合
     */
    @Override
    public List<EngMeterageChange> selectChangeList(EngMeterageChange model) {
        return detailChangeMapper.selectModelList(model);
    }

    /**
     * 查询工程计量其他支付项目列表
     *
     * @param model 工程计量其他支付项目实体
     * @return 工程计量其他支付项目集合
     */
    @Override
    public List<EngMeterageOther> selectOtherList(EngMeterageOther model) {
        return detailOtherMapper.selectModelList(model);
    }

    /**
     * 查询工程计量-计量明细附件列表
     * @param model 工程计量-计量明细附件实体
     * @return 工程计量-计量明细附件集合
     */
    @Override
    public List<EngMeterageDetailAnnex> selectAnnexList(EngMeterageDetailAnnex model) {
        return detailAnnexMapper.selectModelList(model);
    }

    /**
     * 工程计量合同清单保存
     *
     * @param masterId 工程计量主表ID
     * @param ids 计量清单ID集合
     * @return 结果
     */
    @Override
    public int saveContract(Long masterId, String ids) {
        List<ProBoqMeterage> meterageList = meterageMapper.selectModelListByIds(Convert.toStrArray(ids));
        List<EngMeterageContract> details = new ArrayList<>();
        // 当前登录用户
        SysUser loginUser = userMapper.selectUserById(SecurityUtils.getUserId());
        for (ProBoqMeterage meterage : meterageList) {
            EngMeterageContract detail = new EngMeterageContract();
            detail.setMasterId(masterId);
            detail.setMeterageBoqCode(meterage.getMeterageBoqCode());
            detail.setBoqCode(meterage.getBoqCode());
            detail.setBoqName(meterage.getBoqName());
            detail.setAncestors(meterage.getAncestors());
            detail.setOrderNum(meterage.getOrderNum());
            detail.setUnit(meterage.getUnit());
            detail.setPrice(meterage.getPrice());
            detail.setPlace(meterage.getPlace());
            detail.setItem(meterage.getItem());
            detail.setBlueprint(meterage.getBlueprint());
            detail.setBeginStation(meterage.getBeginStation());
            detail.setEndStation(meterage.getEndStation());
            detail.setHasAnnex(Constants.NO);
            detail.setHasSketch(Constants.NO);
            detail.setIsEdit(Constants.NO);
            detail.setComplete(Constants.NO);
            detail.setDept(loginUser.getDeptId());
            detail.setDeptName(loginUser.getDept().getDeptName());
            detail.setUser(loginUser.getUserName());
            detail.setUserName(loginUser.getNickName());
            detail.setCreateBy(loginUser.getUserName());
            detail.setCreateTime(DateUtils.getNowDate());
            String uuid = IdUtils.simpleUuid();
            detail.setAnnexUuid(uuid);
            details.add(detail);
        }
        // 批量插入
        detailContractMapper.insertBatch(details);
        return 1;
    }

    /**
     * 工程计量变更清单保存
     *
     * @param masterId 工程计量主表ID
     * @param ids 计量清单ID集合
     * @return 结果
     */
    @Override
    public int saveChange(Long masterId, String ids) {
        List<ProBoqMeterage> meterageList = meterageMapper.selectModelListByIds(Convert.toStrArray(ids));
        List<EngMeterageChange> details = new ArrayList<>();
        // 当前登录用户
        SysUser loginUser = userMapper.selectUserById(SecurityUtils.getUserId());
        for (ProBoqMeterage meterage : meterageList) {
            EngMeterageChange detail = new EngMeterageChange();
            detail.setMasterId(masterId);
            detail.setMeterageBoqCode(meterage.getMeterageBoqCode());
            detail.setBoqCode(meterage.getBoqCode());
            detail.setBoqName(meterage.getBoqName());
            detail.setAncestors(meterage.getAncestors());
            detail.setOrderNum(meterage.getOrderNum());
            detail.setUnit(meterage.getUnit());
            detail.setPrice(meterage.getPrice());
            detail.setPlace(meterage.getPlace());
            detail.setItem(meterage.getItem());
            detail.setBlueprint(meterage.getBlueprint());
            detail.setBeginStation(meterage.getBeginStation());
            detail.setEndStation(meterage.getEndStation());
            detail.setHasAnnex(Constants.NO);
            detail.setHasSketch(Constants.NO);
            detail.setIsEdit(Constants.NO);
            detail.setComplete(Constants.NO);
            detail.setDept(loginUser.getDeptId());
            detail.setDeptName(loginUser.getDept().getDeptName());
            detail.setUser(loginUser.getUserName());
            detail.setUserName(loginUser.getNickName());
            detail.setCreateBy(loginUser.getUserName());
            detail.setCreateTime(DateUtils.getNowDate());
            String uuid = IdUtils.simpleUuid();
            detail.setAnnexUuid(uuid);
            details.add(detail);
        }
        // 批量插入
        detailChangeMapper.insertBatch(details);
        return 1;
    }

    /**
     * 新增工程计量-计量明细附件
     *
     * @param model 附件
     * @param annexType 附件类型 1附件 2草图
     * @param uuid uuid
     * @param type 类型 0合同 1变更 2其他
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertAnnex(EngMeterageDetailAnnex model, Integer annexType, String uuid, Integer type) {
        int result = 0;
        // 查询一下文件数量。数量等于0，则需要更新状态
        int count = detailAnnexMapper.getFileCountByAnnexType(uuid, annexType, type);
        if (count == 0) {
            result = 1;
        }
        if (type == 0) {
            // 更新合同清单
            if (annexType == 1) {
                detailContractMapper.updateAnnexStatus(uuid, Constants.YES);
            } else {
                detailContractMapper.updateSketchStatus(uuid, Constants.YES);
            }
        } else if (type == 1) {
            // 更新变更清单
            if (annexType == 1) {
                // 查询一下附件数量。如果数量已经大于1，则不需要更新状态
                detailChangeMapper.updateAnnexStatus(uuid, Constants.YES);
            } else {
                // 查询一下草图数量。如果数量已经大于1，则不需要更新状态
                detailChangeMapper.updateSketchStatus(uuid, Constants.YES);
            }
        } else {
            // 更新其他支付项目
            detailOtherMapper.updateAnnexStatus(uuid, Constants.YES);
        }
        detailAnnexMapper.insert(model);
        return result;
    }

    /**
     * 根据主键ID获取工程计量合同清单
     *
     * @param id 合同计量ID
     * @return 合同清单详情
     */
    @Override
    public EngMeterageContract getDetailContractById(Long id) {
        return detailContractMapper.getModelById(id);
    }

    /**
     * 根据主键ID获取工程计量变更清单
     *
     * @param id 变更计量ID
     * @return 变更清单详情
     */
    @Override
    public EngMeterageChange getDetailChangeById(Long id) {
        return detailChangeMapper.getModelById(id);
    }

    /**
     * 根据主键ID获取工程计量其他支付项目
     *
     * @param id 其他支付项目ID
     * @return 其他支付项目详情
     */
    @Override
    public EngMeterageOther getDetailOtherById(Long id) {
        return detailOtherMapper.getModelById(id);
    }

    /**
     * 根据主键ID和用户获取工程计量填报说明
     *
     * @param masterId 工程计量主表主键
     * @param user 用户
     * @return 填报说明详情
     */
    @Override
    public EngMeterageExplain getDetailExplainByUser(Long masterId, String user) {
        return detailExplainMapper.getModelByUser(masterId, user);
    }

    /**
     * 根据主键ID获取附件信息
     * @param id 附件ID
     * @return 附件详情
     */
    @Override
    public EngMeterageDetailAnnex getDetailAnnexById(Long id) {
        return detailAnnexMapper.getModelById(id);
    }

    /**
     * 修改工程计量-合同清单详情
     *
     * @param model 工程计量-合同清单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDetailContract(EngMeterageContract model) {
        // 修改合同清单的已计量数量和剩余数量
        ProBoqMeterage meterage = meterageMapper.getModelByCode(model.getMeterageBoqCode());
        // 取出原有数据
        EngMeterageContract old = detailContractMapper.getModelById(model.getDetailContractId());
        BigDecimal oldAmount = old.getAmount() == null ? new BigDecimal(0) : old.getAmount();
        BigDecimal newAmount = model.getAmount() == null ? new BigDecimal(0) : model.getAmount();
        BigDecimal oldTotal = old.getTotal() == null ? new BigDecimal(0) : old.getTotal();
        BigDecimal newTotal = model.getTotal() == null ? new BigDecimal(0) : model.getTotal();
        // 值发生改变
        if (oldAmount.compareTo(newAmount) != 0) {
            // 更新计量清单里面的已计量数量和剩余数量
            BigDecimal alreadyAmount = meterage.getAlreadyAmount() == null ? new BigDecimal(0) : meterage.getAlreadyAmount();
            BigDecimal remainderAmount = meterage.getRemainderAmount() == null ? new BigDecimal(0) : meterage.getRemainderAmount();
            alreadyAmount = alreadyAmount.subtract(oldAmount).add(newAmount);
            remainderAmount = remainderAmount.add(oldAmount).subtract(newAmount);
            meterage.setAlreadyAmount(alreadyAmount);
            meterage.setRemainderAmount(remainderAmount);
            // 更新计量清单里面的已计量金额和剩余金额
            BigDecimal alreadyTotal = meterage.getAlreadyTotal() == null ? new BigDecimal(0) : meterage.getAlreadyTotal();
            BigDecimal remainderTotal = meterage.getRemainderTotal() == null ? new BigDecimal(0) : meterage.getRemainderTotal();
            alreadyTotal = alreadyTotal.subtract(oldTotal).add(newTotal);
            remainderTotal = remainderTotal.add(oldTotal).subtract(newTotal);
            meterage.setAlreadyTotal(alreadyTotal);
            meterage.setRemainderTotal(remainderTotal);
            // 是否完成需要判断是否为负数清单, flag为true是正数清单，flag为false是负数清单
            boolean flag = true;
            BigDecimal amount = meterage.getAmount() == null ? new BigDecimal(0) : meterage.getAmount();
            if (amount.compareTo(new BigDecimal(0)) < 0) {
                flag = false;
            }
            // 正清单：如果剩余数量小于等于0的时候，该清单计量完成，负清单：如果剩余数量大于等于0的时候，该清单计量完成
            if (flag) {
                if (meterage.getRemainderAmount().compareTo(new BigDecimal(0)) <= 0) {
                    meterage.setComplete(Constants.YES);
                    model.setComplete(Constants.YES);
                } else {
                    meterage.setComplete(Constants.NO);
                    model.setComplete(Constants.NO);
                }
            } else {
                if (meterage.getRemainderAmount().compareTo(new BigDecimal(0)) >= 0) {
                    meterage.setComplete(Constants.YES);
                    model.setComplete(Constants.YES);
                } else {
                    meterage.setComplete(Constants.NO);
                    model.setComplete(Constants.NO);
                }
            }
            // 更新合同清单的已计量数量,剩余数量,已计量金额,剩余金额
            meterageMapper.update(meterage);
            // 修改其他用户的is_edit = 1
            detailContractMapper.updateIsEdit(model.getAnnexUuid(), model.getDetailContractId(), newAmount);
        }
        model.setUpdateBy(SecurityUtils.getUsername());
        model.setUpdateTime(DateUtils.getNowDate());
        return detailContractMapper.update(model);
    }

    /**
     * 修改工程计量-变更清单详情
     *
     * @param model 工程计量-变更清单
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDetailChange(EngMeterageChange model) {
        // 修改合同清单的已计量数量和剩余数量
        ProBoqMeterage meterage = meterageMapper.getModelByCode(model.getMeterageBoqCode());
        // 取出原有数据
        EngMeterageChange old = detailChangeMapper.getModelById(model.getDetailChangeId());
        BigDecimal oldAmount = old.getAmount() == null ? new BigDecimal(0) : old.getAmount();
        BigDecimal newAmount = model.getAmount() == null ? new BigDecimal(0) : model.getAmount();
        BigDecimal oldTotal = old.getTotal() == null ? new BigDecimal(0) : old.getTotal();
        BigDecimal newTotal = model.getTotal() == null ? new BigDecimal(0) : model.getTotal();
        // 值发生改变
        if (oldAmount.compareTo(newAmount) != 0) {
            BigDecimal alreadyAmount = meterage.getAlreadyAmount() == null ? new BigDecimal(0) : meterage.getAlreadyAmount();
            BigDecimal remainderAmount = meterage.getRemainderAmount() == null ? new BigDecimal(0) : meterage.getRemainderAmount();
            alreadyAmount = alreadyAmount.subtract(oldAmount).add(newAmount);
            remainderAmount = remainderAmount.add(oldAmount).subtract(newAmount);
            meterage.setAlreadyAmount(alreadyAmount);
            meterage.setRemainderAmount(remainderAmount);
            // 更新计量清单里面的已计量金额和剩余金额
            BigDecimal alreadyTotal = meterage.getAlreadyTotal() == null ? new BigDecimal(0) : meterage.getAlreadyTotal();
            BigDecimal remainderTotal = meterage.getRemainderTotal() == null ? new BigDecimal(0) : meterage.getRemainderTotal();
            alreadyTotal = alreadyTotal.subtract(oldTotal).add(newTotal);
            remainderTotal = remainderTotal.add(oldTotal).subtract(newTotal);
            meterage.setAlreadyTotal(alreadyTotal);
            meterage.setRemainderTotal(remainderTotal);
            // 是否完成需要判断是否为负数清单, flag为true是正数清单，flag为false是负数清单
            boolean flag = true;
            BigDecimal amount = meterage.getAmount() == null ? new BigDecimal(0) : meterage.getAmount();
            if (amount.compareTo(new BigDecimal(0)) < 0) {
                flag = false;
            }
            // 正清单：如果剩余数量小于等于0的时候，该清单计量完成，负清单：如果剩余数量大于等于0的时候，该清单计量完成
            if (flag) {
                if (meterage.getRemainderAmount().compareTo(new BigDecimal(0)) <= 0) {
                    meterage.setComplete(Constants.YES);
                    model.setComplete(Constants.YES);
                } else {
                    meterage.setComplete(Constants.NO);
                    model.setComplete(Constants.NO);
                }
            } else {
                if (meterage.getRemainderAmount().compareTo(new BigDecimal(0)) >= 0) {
                    meterage.setComplete(Constants.YES);
                    model.setComplete(Constants.YES);
                } else {
                    meterage.setComplete(Constants.NO);
                    model.setComplete(Constants.NO);
                }
            }
            // 更新合同清单的已计量数量,剩余数量,已计量金额,剩余金额
            meterageMapper.update(meterage);
            // 修改其他用户的is_edit = 1
            detailChangeMapper.updateIsEdit(model.getAnnexUuid(), model.getDetailChangeId(), newAmount);
        }
        model.setUpdateBy(SecurityUtils.getUsername());
        model.setUpdateTime(DateUtils.getNowDate());
        return detailChangeMapper.update(model);
    }

    /**
     * 修改工程计量-其他支付项目详情
     *
     * @param model 工程计量-其他支付项目
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDetailOther(EngMeterageOther model) {
        // 取出原有数据
        EngMeterageOther old = detailOtherMapper.getModelById(model.getDetailOtherId());
        BigDecimal oldTotal = old.getTotal() == null ? new BigDecimal(0) : old.getTotal();
        BigDecimal newTotal = model.getTotal() == null ? new BigDecimal(0) : model.getTotal();
        // 值发生改变
        if (oldTotal.compareTo(newTotal) != 0) {
            // 修改其他用户的is_edit = 1
            detailOtherMapper.updateIsEdit(model.getAnnexUuid(), model.getDetailOtherId(), newTotal);
        }
        model.setUpdateBy(SecurityUtils.getUsername());
        model.setUpdateTime(DateUtils.getNowDate());
        return detailOtherMapper.update(model);
    }

    /**
     * 修改工程计量-填报说明详情
     *
     * @param model 工程计量-填报说明
     * @return 结果
     */
    @Override
    public int updateDetailExplain(EngMeterageExplain model) {
        model.setUpdateBy(SecurityUtils.getUsername());
        model.setUpdateTime(DateUtils.getNowDate());
        return detailExplainMapper.update(model);
    }

    /**
     * 批量删除工程计量-合同清单详情
     *
     * @param ids 主键集合
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteContractByIds(Long[] ids) {
        EngMeterageContract first = detailContractMapper.getModelById(ids[0]);
        EngMeterageMaster master = masterMapper.getModelById(first.getMasterId());
        String loginUserName = SecurityUtils.getUsername();
        // 当前登录用户是否是创建者
        boolean loginUserIsCreateBy = false;
        if (loginUserName.equals(master.getCreateBy())) {
            loginUserIsCreateBy = true;
        }
        for (int i = 0; i < ids.length; i++) {
            EngMeterageContract detailContract = detailContractMapper.getModelById(ids[i]);
            // 还原合同清单里的已计量数量和剩余数量
            BigDecimal amount = detailContract.getAmount() == null ?  BigDecimal.ZERO : detailContract.getAmount();
            BigDecimal total = detailContract.getTotal() == null ? BigDecimal.ZERO : detailContract.getTotal();
            ProBoqMeterage meterage = meterageMapper.getModelByMeterageBoqCode(detailContract.getMeterageBoqCode());
            BigDecimal alreadyAmount = meterage.getAlreadyAmount() == null ?  BigDecimal.ZERO : meterage.getAlreadyAmount();
            BigDecimal remainderAmount = meterage.getRemainderAmount() == null ?  BigDecimal.ZERO : meterage.getRemainderAmount();
            BigDecimal alreadyTotal = meterage.getAlreadyTotal() == null ? BigDecimal.ZERO : meterage.getAlreadyTotal();
            BigDecimal remainderTotal = meterage.getRemainderTotal() == null ? BigDecimal.ZERO : meterage.getRemainderTotal();
            meterage.setAlreadyAmount(alreadyAmount.subtract(amount));
            meterage.setRemainderAmount(remainderAmount.add(amount));
            meterage.setAlreadyTotal(alreadyTotal.subtract(total));
            meterage.setRemainderTotal(remainderTotal.add(total));
            // 设置工程量清单是否完成，需要判断正负清单问题
            int result = meterage.getRemainderAmount().compareTo(BigDecimal.ZERO);
            boolean flag = true;
            BigDecimal meterageAmount = meterage.getAmount() == null ? BigDecimal.ZERO : meterage.getAmount();
            if (meterageAmount.compareTo(BigDecimal.ZERO) < 0) {
                flag = false;
            }
            if (flag) {
                if (result <= 0) {
                    meterage.setComplete(Constants.YES);
                } else {
                    meterage.setComplete(Constants.NO);
                }
            } else {
                if (result >= 0) {
                    meterage.setComplete(Constants.YES);
                } else {
                    meterage.setComplete(Constants.NO);
                }
            }
            meterageMapper.update(meterage);
            // 删除工程计量-合同计量清单
            detailContractMapper.delete(ids[i]);
            // 删除草图和附件
            if (loginUserIsCreateBy) {
                // 删除附件和草图文件
                String path = MasterConfig.getUploadAnnexPath()
                        + "/" + Constants.MENU_TYPE_ENGINEERING
                        + "/" + master.getUuid()
                        + "/meterage/" + detailContract.getAnnexUuid();
                FileUtils.deleteDirectory(new File(path));
                // 删除文件记录
                detailAnnexMapper.deleteByUuid(detailContract.getAnnexUuid());
            }
        }
        return 1;
    }

    /**
     * 批量删除工程计量-变更清单详情
     *
     * @param ids 主键集合
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteChangeByIds(Long[] ids) {
        EngMeterageChange first = detailChangeMapper.getModelById(ids[0]);
        EngMeterageMaster master = masterMapper.getModelById(first.getMasterId());
        String loginUserName = SecurityUtils.getUsername();
        // 当前登录用户是否是创建者
        boolean loginUserIsCreateBy = false;
        if (loginUserName.equals(master.getCreateBy())) {
            loginUserIsCreateBy = true;
        }
        for (int i = 0; i < ids.length; i++) {
            EngMeterageChange detailChange = detailChangeMapper.getModelById(ids[i]);
            // 还原合同清单里的已计量数量和剩余数量
            BigDecimal amount = detailChange.getAmount() == null ? BigDecimal.ZERO : detailChange.getAmount();
            BigDecimal total = detailChange.getTotal() == null ? BigDecimal.ZERO : detailChange.getTotal();
            ProBoqMeterage meterage = meterageMapper.getModelByMeterageBoqCode(detailChange.getMeterageBoqCode());
            BigDecimal alreadyAmount = meterage.getAlreadyAmount() == null ? BigDecimal.ZERO : meterage.getAlreadyAmount();
            BigDecimal remainderAmount = meterage.getRemainderAmount() == null ? BigDecimal.ZERO : meterage.getRemainderAmount();
            BigDecimal alreadyTotal = meterage.getAlreadyTotal() == null ? BigDecimal.ZERO : meterage.getAlreadyTotal();
            BigDecimal remainderTotal = meterage.getRemainderTotal() == null ? BigDecimal.ZERO : meterage.getRemainderTotal();
            meterage.setAlreadyAmount(alreadyAmount.subtract(amount));
            meterage.setRemainderAmount(remainderAmount.add(amount));
            meterage.setAlreadyTotal(alreadyTotal.subtract(total));
            meterage.setRemainderTotal(remainderTotal.add(total));
            // 设置工程量清单是否完成
            int result = meterage.getRemainderAmount().compareTo(BigDecimal.ZERO);
            boolean flag = true;
            BigDecimal meterageAmount = meterage.getAmount() == null ? BigDecimal.ZERO : meterage.getAmount();
            if (meterageAmount.compareTo(BigDecimal.ZERO) < 0) {
                flag = false;
            }
            if (flag) {
                if (result <= 0) {
                    meterage.setComplete(Constants.YES);
                } else {
                    meterage.setComplete(Constants.NO);
                }
            } else {
                if (result >= 0) {
                    meterage.setComplete(Constants.YES);
                } else {
                    meterage.setComplete(Constants.NO);
                }
            }
            meterageMapper.update(meterage);
            // 删除工程计量-合同计量清单
            detailChangeMapper.delete(ids[i]);
            // 删除草图和附件
            if (loginUserIsCreateBy) {
                // 删除附件和草图文件
                String path = MasterConfig.getUploadAnnexPath()
                        + "/" + Constants.MENU_TYPE_ENGINEERING
                        + "/" + master.getUuid()
                        + "/meterage/" + detailChange.getAnnexUuid();
                FileUtils.deleteDirectory(new File(path));
                // 删除文件记录
                detailAnnexMapper.deleteByUuid(detailChange.getAnnexUuid());
            }
        }
        return 1;
    }

    /**
     * 删除工程计量-附件详情
     * @param id 主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteAnnexById(Long id) {
        // 删除附件记录，并更新明细状态，返回刷新状态 0为不刷新 1为刷新
        int result = 0;
        EngMeterageDetailAnnex annex = detailAnnexMapper.getModelById(id);
        // 因为草图只能上传一个所以直接更新状态
        if (annex.getAnnexType() == 2) {
            if (annex.getType() == 0) {
                // 合同
                detailContractMapper.updateSketchStatus(annex.getUuid(), Constants.NO);
            } else {
                // 变更
                detailChangeMapper.updateSketchStatus(annex.getUuid(), Constants.NO);
            }
            result = 1;
        } else {
            int count = 0;
            count = detailAnnexMapper.getFileCountByAnnexType(annex.getUuid(), annex.getAnnexType(), annex.getType());
            // 附件有多个数量，所以需要判断数量
            if (annex.getType() == 0) {
                // 合同
                if (count == 1) {
                    result = 1;
                    detailContractMapper.updateAnnexStatus(annex.getUuid(), Constants.NO);
                }
            } else if (annex.getType() == 1) {
                // 变更
                if (count == 1) {
                    result = 1;
                    detailChangeMapper.updateAnnexStatus(annex.getUuid(), Constants.NO);
                }
            } else {
                // 其他
                if (count == 1) {
                    result = 1;
                    detailOtherMapper.updateAnnexStatus(annex.getUuid(), Constants.NO);
                }
            }
        }
        detailAnnexMapper.delete(id);
        return result;
    }

    /**
     * 同步其他支付项目固定值
     * @param masterId 主表主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int syncDetailItem(Long masterId) {
        EngMeterageMaster master = masterMapper.getModelById(masterId);
        // 删除支付项目相关附件
        EngMeterageOther search = new EngMeterageOther();
        search.setMasterId(master.getMasterId());
        search.setUser(master.getCurrentUser());
        List<EngMeterageOther> list = detailOtherMapper.selectModelList(search);
        for (EngMeterageOther other : list) {
            // 删除附件
            String path = MasterConfig.getUploadAnnexPath()
                    + "/" + Constants.MENU_TYPE_ENGINEERING
                    + "/" + master.getUuid()
                    + "/meterage/" + other.getAnnexUuid();
            FileUtils.deleteDirectory(new File(path));
            // 删除文件记录
            detailAnnexMapper.deleteByUuid(other.getAnnexUuid());
        }
        // 先删除当前用户下的支付项目
        detailOtherMapper.deleteByUser(master.getMasterId(), master.getCurrentUser());
        SysUser currentWorkflowUser = userMapper.selectUserByUserName(master.getCurrentUser());
        List<EngMeterageOther> others = createMeterageOtherList(master, currentWorkflowUser);
        detailOtherMapper.insertBatch(others);
        return 1;
    }

    /**
     * 创建工程计量-其他支付项目固定值集合
     *
     * @param master 主表信息
     * @param user 用户
     * @return 固定值支付项目集合
     */
    @Override
    public List<EngMeterageOther> createMeterageOtherList(EngMeterageMaster master, SysUser user) {
        // 添加工程支付项目
        ProPaymentItems search = new ProPaymentItems();
        search.setProjectId(master.getProjectId());
        search.setComputeMode(Constants.FIXED_VALUE);
        search.setItemStatus(Constants.SUCCESS);
        List<ProPaymentItems> paymentItems = paymentItemsMapper.selectModelList(search);
        List<EngMeterageOther> others = new ArrayList<>();
        for (ProPaymentItems item : paymentItems) {
            EngMeterageOther other = new EngMeterageOther();
            other.setMasterId(master.getMasterId());
            other.setItemCode(item.getItemCode());
            other.setItemName(item.getItemName());
            other.setItemOrder(item.getItemOrder());
            other.setAnnexUuid(IdUtils.simpleUuid());
            other.setHasAnnex(Constants.NO);
            other.setIsEdit(Constants.NO);
            other.setDept(user.getDeptId());
            other.setDeptName(user.getDept().getDeptName());
            other.setUser(user.getUserName());
            other.setUserName(user.getNickName());
            other.setCreateBy(SecurityUtils.getUsername());
            other.setCreateTime(DateUtils.getNowDate());
            others.add(other);
        }
        return others;
    }

    /**
     * 复制清单--合同工程计量清单
     *
     * @param detailContractId 复制ID
     * @param amount 数量
     * @return 结果
     */
    @Override
    public int copy(Long detailContractId, Integer amount) {
        EngMeterageContract detail = detailContractMapper.getModelById(detailContractId);
        List<EngMeterageContract> list = new ArrayList<>();
        for (int i = 0; i < amount; i++) {
            EngMeterageContract copy = new EngMeterageContract();
            copy.setMasterId(detail.getMasterId());
            copy.setMeterageBoqCode(detail.getMeterageBoqCode());
            copy.setBoqCode(detail.getBoqCode());
            copy.setBoqName(detail.getBoqName());
            copy.setAncestors(detail.getAncestors());
            copy.setOrderNum(detail.getOrderNum());
            copy.setUnit(detail.getUnit());
            copy.setPrice(detail.getPrice());
            copy.setBeginStation(detail.getBeginStation());
            copy.setEndStation(detail.getEndStation());
            copy.setPlace(detail.getPlace());
            copy.setItem(detail.getItem());
            copy.setFormula(detail.getFormula());
            copy.setBlueprint(detail.getBlueprint());
            copy.setCertificateNo(detail.getCertificateNo());
            copy.setIsEdit(Constants.NO);
            copy.setComplete(Constants.NO);
            copy.setAnnexUuid(IdUtils.simpleUuid());
            copy.setDept(detail.getDept());
            copy.setDeptName(detail.getDeptName());
            copy.setUser(detail.getUser());
            copy.setUserName(detail.getUserName());
            list.add(copy);
        }
        // 批量插入
        detailContractMapper.insertBatch(list);
        return 1;
    }
}
